<!-- 新闻列表 -->
<template>
    <div class="pageListBox">
        <div class="cardAdmin">
            <div class="formNewAdmin" v-if="formshow">
                <div class="formSearch">
                    <span class="namename">标题关键词</span>
                    <el-input size="mini" style="flex: 3" v-model="form.keyword"></el-input>
                </div>
                <div class="souSuoYouCe">
                    <el-button icon="el-icon-refresh" size="mini" class="white-button" @click="resetForm()">重置</el-button>
                    <el-button class="black-button" icon="el-icon-search" size="mini"
                        @click="get_data('btn')">搜索</el-button>
                </div>
            </div>
        </div>
        <div class="btnBoxList">
            <div class="btns">
                <el-button class="green-button" size="mini" icon="el-icon-plus" plain @click="addbtn()">Add</el-button>
                <el-button class="black-button" size="mini" icon="el-icon-refresh" plain
                    @click="get_data()">刷新表格</el-button>
            </div>
            <div class="formbtns">
                <div style="height: 100%;;background-color: #f4f4f4;display: flex;">
                    <div class="qweqweasdasd" style="display: none;">
                        <el-dropdown trigger="click" placement="bottom">

                            <div class="btnList22">
                                <i class="el-icon-s-grid"></i>
                                <i style="font-size: 14px;" class="el-icon-caret-bottom"></i>
                            </div>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item v-for="col in allColumns" :key="col.prop">
                                    <el-checkbox v-model="selectedColumns" :label="col.prop">
                                        {{ col.label }}
                                    </el-checkbox>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="poipoi1">
                        <el-dropdown @command="exportTable" class="popo1cli" trigger="click" placement="bottom">
                            <span class="el-dropdown-link">
                                <i style="font-size: 18px;" class="el-icon-download"></i>
                                <i style="font-size: 14px;" class="el-icon-caret-bottom"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="json">JSON</el-dropdown-item>
                                <el-dropdown-item command="xml">XML</el-dropdown-item>
                                <el-dropdown-item command="csv">CSV</el-dropdown-item>
                                <el-dropdown-item command="txt">TXT</el-dropdown-item>
                                <el-dropdown-item command="word">Word</el-dropdown-item>
                                <el-dropdown-item command="excel">Excel</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="poipoi2">
                        <i style="font-size: 18px;cursor: pointer;" class=" el-icon-search" @click="showform"></i>

                    </div>
                </div>
            </div>
        </div>
        <!-- 表格 -->
        <el-table v-table-resize  border highlight-current-row style="max-height: 70vh;overflow: auto;" :data="tableData" cell-class-name="rowlist"
            class="x1919" ref="tableRef" size="mini" v-loading="table_loading">
            <!-- row-key="uniqueId"  :row-class-name="tableRowStyle" :tree-props="{ children: 'menuids', hasChildren: 'hasChildren' }" -->

            <el-table-column prop="id" fixed="left"  label="id" width="auto" align="center" min-width="80px">
            </el-table-column>
            <el-table-column prop="title" label="标题" width="auto" align="center" min-width="180px">
            </el-table-column>
            <el-table-column prop="byline" label="作者" width="auto" align="center" min-width="140px">
            </el-table-column>
            <el-table-column prop="avatar" label="头像" width="auto" align="center" min-width="120px">
                <template slot-scope="scope">
                    <el-image style="height: 22px" :src="url + scope.row.avatar"
                        :preview-src-list="[url + scope.row.avatar]">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="image" label="配图" width="auto" align="center" min-width="120px">
                <template slot-scope="scope">
                    <el-image style="height: 22px" :src="url + scope.row.image" :preview-src-list="[url + scope.row.image]">
                    </el-image>
                </template>
            </el-table-column>

            <el-table-column prop="crawl_time" label="抓取时间" width="auto" align="center" min-width="150px">
            </el-table-column>

            <el-table-column prop="publish_time" label="发布时间" width="auto" align="center" min-width="150px">
            </el-table-column>

            <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                    <el-button @click="tableEditing(scope.row)" class="green-button" icon="el-icon-edit" type="info" plain
                        size="mini"></el-button>
                    <el-button @click="del_data(scope.row.id)" class="red-button" type="info" plain size="mini"
                        icon="el-icon-delete"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="fenye11">
            <div style="display: flex;align-items: center;">{{ `当前第 ${currentPage} 页，每页 ${pagesize} 条记录` }}</div>
            <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
                @current-change="current_change"></el-pagination>
        </div>
        <!-- 弹窗 -->
        <el-dialog :close-on-click-modal="false" :modal="true" ref="myDialog" :fullscreen="isFullscreen" v-dialog-drag
            top="35px" :visible.sync="dialogVisibleAdd" :before-close="beforeClose"
            :custom-class="isFullscreen ? 'dialogqp' : ''">
            <div slot="title">
                <span style="color:#fff">新增</span>
                <button class="dialogTitle" @click="toggleFullscreen">
                    <i :class="['el-icon', isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen']"
                        style="color: #9c95a4;"></i>
                </button>
            </div>

            <el-form :model="formAdd" :rules="rulesAdd" ref="formAdd" class="demo-formAdd">
                <el-form-item label="作者头像" class="uploaditem-userlist">
                    <el-upload class="avatar-uploader-userlist" action="#" :on-change="handleFileChangetx"
                        :auto-upload="false" :show-file-list="false" :before-upload="beforeUpload" name="file"
                        ref="uploadertx">
                        <img v-if="imageUrltx.local" :src="imageUrltx.local" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="配图" class="uploaditem-userlist">
                    <el-upload ref="uploaderpt" class="avatar-uploader-userlist" :on-change="handleFileChangept"
                        action="javascript:void(0)" :auto-upload="false" :show-file-list="false"
                        :before-upload="beforeUpload" name="file">
                        <img v-if="imageUrlpt.local" :src="imageUrlpt.local" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item label="新闻作者" prop="byline">
                    <el-input size="mini" v-model="formAdd.byline">
                        <template #prefix></template>
                    </el-input>
                </el-form-item>

                <el-form-item label="新闻标题" prop="title">
                    <el-input size="mini" v-model="formAdd.title">
                        <template #prefix></template>
                    </el-input>
                </el-form-item>

                <el-form-item label="发布时间" prop="publish_time">
                    <el-date-picker class="diaformart" maxlength="200" size="mini" show-word-limit
                        v-model="formAdd.publish_time" type="datetime" placeholder="选择日期时间"
                        value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" :default-time="'23:59:59'" />
                </el-form-item>

                <el-form-item label="内容">
                    <!-- <quill-editor v-if="editorReady" ref="myQuillEditor" v-model="content" :options="editorOption" /> -->
                    <editor v-if="editorReady" v-model="content" ref="myQuillEditor" :init="initOptions" />
                </el-form-item>
            </el-form>

            <template slot="footer">
                <div class="fbtns">
                    <el-button class="purple-button" size="mini" @click="add_data" :loading="btnAdd" plain>确认新增</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" :modal="true" ref="myDialog" v-dialog-drag :fullscreen="isFullscreen"
            top="35px" title="更新" :visible.sync="dialogVisibleEdit" v-loading="dialogVisibleEditLoading"
            :before-close="beforeClose" :custom-class="isFullscreen ? 'dialogqp' : ''">


            <div slot="title">
                <span style="color:#fff">更新</span>
                <button slot="title" class="dialogTitle" @click="toggleFullscreen">
                    <i :class="['el-icon', isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen']"
                        style="color: #9c95a4;"></i>
                </button>
            </div>


            <el-form :model="formEdit" :rules="rulesEdit" ref="formEdit" class="demo-formEdit">

                <el-form-item label="头像" class="uploaditem-userlist">
                    <el-upload ref="uploadertx" class="avatar-uploader-userlist" :on-change="handleFileChangetx"
                        action="javascript:void(0)" :auto-upload="false" :show-file-list="false"
                        :before-upload="beforeUpload" name="file">
                        <img v-if="imageUrltx.local" :src="imageUrltx.local" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="配图" class="uploaditem-userlist">
                    <el-upload ref="uploaderpt" class="avatar-uploader-userlist" :on-change="handleFileChangept"
                        action="javascript:void(0)" :auto-upload="false" :show-file-list="false"
                        :before-upload="beforeUpload" name="file">
                        <img v-if="imageUrlpt.local" :src="imageUrlpt.local" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                </el-form-item> <el-form-item label="新闻作者" prop="byline">
                    <el-input size="mini" v-model="formEdit.byline">
                        <template #prefix></template>
                    </el-input>
                </el-form-item>

                <el-form-item label="新闻标题" prop="title">
                    <el-input size="mini" v-model="formEdit.title">
                        <template #prefix></template>
                    </el-input>
                </el-form-item>

                <el-form-item label="发布时间" prop="publish_time">
                    <el-date-picker class="diaformart" maxlength="200" size="mini" show-word-limit
                        v-model="formEdit.publish_time" type="datetime" placeholder="选择日期时间"
                        value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" :default-time="'23:59:59'" />
                </el-form-item>

                <el-form-item label="内容">
                    <!-- <quill-editor v-if="editorReady" ref="myQuillEditor" v-model="content" :options="editorOption" /> -->
                    <editor v-if="editorReady" v-model="content" ref="myQuillEditor" :init="initOptions" />
                </el-form-item>
            </el-form>

            <template slot="footer">
                <div class="fbtns">
                    <el-button class="black-button" size="mini" plain @click="upd_data" :loading="btnEdit">确认修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script>
import { news_list, new_news_added, news_editor, news_deletion, url, upload_pictures } from "@/utils/api";
import moment from "moment";
import 'tinymce/tinymce'
import 'tinymce/themes/silver'
// import 'tinymce/icons/default'

// 按需导入插件
import 'tinymce/plugins/link'
import 'tinymce/plugins/image'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/code'
import 'tinymce/plugins/fullscreen'

import Editor from '@tinymce/tinymce-vue'
export default {
    name: "news",
    components: {
        Editor
    },
    data() {
        let disabledDate = (date) => {
            return date.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000;
        };
        const toolbarGroups = [
            ['undo', 'redo'],
            ['formatselect'],
            ['bold', 'italic', 'forecolor', 'backcolor'],
            ['alignleft', 'aligncenter', 'alignright', 'alignjustify'],
            ['bullist', 'numlist', 'outdent', 'indent'],
            ['removeformat', 'help']
        ]
        return {
            initOptions: {
                base_url: '/tinymce',                   // 本地资源路径根目录，对应 public/tinymce
                suffix: '.min',                         // 使用 .min.js 和 .min.css 版本
                skin_url: '/tinymce/skins/ui/oxide',   // 编辑器皮肤路径，默认为 oxide
                height: 400,                            // 编辑器高度（单位 px）
                menubar: true,                          // 是否显示菜单栏（文件 编辑 插入 等）
                language_url: '/tinymce/langs/zh_CN.js', // 中文语言包路径（可选）
                language: 'zh_CN',                      // 设置语言为中文

                plugins: [                              // 插件列表，启用哪些功能模块
                    'advlist',            // 高级列表支持（带符号、有序列表）
                    'autolink',           // 自动检测链接
                    'lists',              // 列表功能
                    'link',               // 插入链接
                    'image',              // 插入图片
                    'charmap',            // 特殊字符
                    'print',              // 打印
                    'preview',            // 内容预览
                    'anchor',             // 插入锚点
                    'searchreplace',      // 查找与替换
                    'visualblocks',       // 显示不可见的 HTML 块（如段落）
                    'code',               // 查看源代码
                    'fullscreen',         // 全屏编辑模式
                    'insertdatetime',     // 插入当前时间和日期
                    'media',              // 插入音频/视频
                    'table',              // 插入表格
                    'paste',              // 粘贴增强（格式保留等）
                    'help',               // 显示帮助面板
                    'wordcount',          // 字数统计
                    'textcolor'           // ✅ 插件：文字颜色（包括字体颜色和背景色）
                ],

                toolbar: toolbarGroups.map(g => g.join(' ')).join(' | '), // 自动转换
                branding: false,                      // 是否显示“Powered by TinyMCE”标志
                resize: true,                         // 是否允许拖动调整编辑器大小
                // ✅ 图片上传回调方法，自定义上传逻辑（例如上传到后端、OSS 等）
                images_upload_handler: this.handleImageUpload

                // images_upload_url: '/api/upload',  // 可选：后端图片上传接口地址
                // automatic_uploads: true            // 自动处理 base64 图片上传（启用 images_upload_handler 时一般不需要）
            },
            isFullscreen: false,
            imageUrltx: {
                local: '',
                file: '',
            },
            imageUrlpt: {
                local: '',
                file: ''
            },

            uploadHeaders: {
                Authorization: "Bearer " + localStorage.getItem("token"),
            },
            pickerOptions: {
                disabledDate,
                // selectableRange 用来限制时分秒的选择，这里要求只能选择当前时间之后到0点的时间点 但应该只限今天
                selectableRange: "00:00:00 - 23:59:59",
            },
            url,
            table_loading: true,
            touristsspeak: [
                {
                    value: 1,
                    label: "是",
                },
                {
                    value: 0,
                    label: "否",
                },
            ],
            dialogVisibleEditLoading: false,
            dialogVisibleEdit: false,
            btnAdd: false,
            btnEdit: false,
            formshow: false,
            exportFormat: '',
            // 下拉框选中的列（存储 prop 值）
            selectedColumns: ['name'], // 默认选中姓名和日期

            // 所有可选的列配置
            allColumns: [
                { prop: 'join_ip', label: '注册IP', width: '140px' },
                { prop: 'join_time', label: '注册时间', width: '140px' },
                { prop: 'login_ip', label: '登录IP', width: '140px' },
                { prop: 'login_time', label: '登录时间', width: '140px' },
                { prop: 'token', label: 'token', width: '140px' },
            ],
            pagesize: 15,
            total: 0,
            options: [
                {
                    value: 1,
                    label: "是",
                },
                {
                    value: 0,
                    label: "否",
                },
            ],
            defaultProps: {
                children: "childs",
                label: "name",
            },
            menuProps: {
                children: "children",
                label: "label",
            },
            formAdd: {
                byline: '',
                title: '',
                publish_time: '',

            },
            formEdit: {
                id: '',
                byline: '',
                title: '',
                publish_time: '',
            },
            form: {
                keyword: "",

            },
            tableData: [
                { id: 1, date: '2023-01-01', group_name: '张三', status: '北京', permissions: '13800138000', name: 'name' },
                { id: 2, date: '2023-01-02', group_name: '李四', status: '上海', permissions: '13900139000', name: 'name' },
            ],
            dialogVisibleAdd: false,
            titles: "",
            name: "",
            nametype: "编辑",
            expandedKeys: [], // 控制哪些行默认展开
            menuData: [], //菜单列表
            userRoleList: [], //角色列表
            articlmenu: [], //文章列表
            draftsmenu: [], //草稿箱列表
            currentNodeData: [],
            currentDraftsKey: [],
            currentPage: 1,
            rulesEdit: {

                byline: [
                    { required: true, message: "请输入作者名称", trigger: "blur" },
                ],
                title: [
                    { required: true, message: "请输入新闻标题", trigger: "blur" },
                ],
                publish_time: [
                    { required: true, message: "请选择发布时间", trigger: "blur" },
                ],



            },
            rulesAdd: {
                byline: [
                    { required: true, message: "请输入作者名称", trigger: "blur" },
                ],
                title: [
                    { required: true, message: "请输入新闻标题", trigger: "blur" },
                ],
                publish_time: [
                    { required: true, message: "请选择发布时间", trigger: "blur" },
                ],
            },
            visible: false,
            editorReady: false, // 控制编辑器渲染
            content: '',

        };
    },
    computed: {
        userRoleId() {
            const user = JSON.parse(localStorage.getItem("user"));
            return user ? user.role_id : null;
        },
        // 计算实际要显示的列
        visibleColumns() {
            return this.allColumns.filter(col =>
                this.selectedColumns.includes(col.prop)
            )
        }
    },
    watch: {
        // 当选择的列变化时，可以在这里添加额外逻辑
        selectedColumns(newVal) {
            console.log('当前显示的列：', newVal)
        },
        "formAdd.publish_time"() {
            this.selectable();
        },
    },
    created() {
        this.get_data();
    },
    mounted() {

    },
    methods: {
        selectable() {
            console.log(this.formAdd.publish_time, 'this.formAdd.publish_time');
            const date = moment(this.formAdd.publish_time).startOf("day").format("x");
            const nowDate = moment().startOf("day").format("x");
            // 如果选择的是今天 则需要禁用已经过去的时间节点

            if (date <= nowDate) {
                // 默认选择的最新时间 是当前时间的两分钟后 （留出2分钟的富裕时间）
                this.pickerOptions.selectableRange = `${moment()
                    .add(1, "minutes")
                    .format("HH:mm:ss")} - 23:59:59`;
            }
            // 如果是以后的日期，则不需要禁用时间节点
            else {
                this.pickerOptions.selectableRange = "00:00:00 - 23:59:59";
            }
        },
        // 文件变化时触发
        handleFileChangetx(file, fileList) {
            console.log(this.$refs.uploadertx);
            // 验证文件（复用原有验证逻辑）
            if (!this.beforeUpload(file.raw)) {
                this.$message.warning('错误文件')
                this.$refs.uploadertx.clearFiles(); // 清空非法文件
                return;
            }

            // 获取文件对象
            console.log('获取的文件:', file.raw);

            // 本地预览：生成临时URL
            this.imageUrltx.local = URL.createObjectURL(file.raw);

            // 如需保留 file 可自行保存
            this.imageUrltx.file = file.raw;
            console.log(this.imageUrltx, 'this.imageUrltx');
            // 清空内部文件列表（避免重复选择相同文件不触发）
            this.$nextTick(() => {
                this.$refs.uploadertx.clearFiles();
            });
        },
        handleFileChangept(file, fileList) {
            // 验证文件（复用原有验证逻辑）
            if (!this.beforeUpload(file.raw)) {
                this.$refs.uploaderpt.clearFiles(); // 清空非法文件
                return;
            }

            // 获取文件对象
            console.log('获取的文件:', file.raw);

            // 本地预览：生成临时URL
            this.imageUrlpt.local = URL.createObjectURL(file.raw);

            // 如需保留 file 可自行保存
            this.imageUrlpt.file = file.raw;
            console.log(this.imageUrlpt, 'this.imageUrlpt');
            // 清空内部文件列表（避免重复选择相同文件不触发）
            this.$nextTick(() => {
                this.$refs.uploaderpt.clearFiles();
            });
        },

        beforeUpload(file) {
            console.log(file, 'filefile');
            const isLt7M = file.size / 1024 / 1024 < 7;
            if (!isLt7M) {
                this.$message.error('上传图片大小不能超过 7MB!');
                return false;
            }
            return isLt7M
        },
        // onQuill({ editor, html, text }) {
        //     console.log('change', html);
        // },
        toggleFullscreen() {
            this.isFullscreen = !this.isFullscreen;

        },
        showform() {
            this.formshow = !this.formshow
        },
        get_time() {
            const now = new Date();
            const formatted = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0');
            return formatted
        },
        // 查询
        async get_data(btn) {
            if (btn == 'btn') this.currentPage = 1
            this.table_loading = true; // 开始加载

            let params = new URLSearchParams();

            params.append('page', this.currentPage);
            params.append('page_size', this.pagesize);

            if (this.form.keyword) params.append('keyword', this.form.keyword);


            let data = `?${params.toString()}`;

            try {
                const res = await news_list(data);
                if (res.data && res.data.code == "200") {
                    this.tableData = res.data.data.data;
                    this.total = res.data.data.total_records;
                } else {
                    this.$message.error(res?.data?.msg || "获取数据失败");
                }
            } catch (err) {
                console.error("获取数据失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.table_loading = false; // 不论成功失败都结束 table_loading
            }
        },
        // 新增
        async add_data() {
            console.log(this.formAdd, 'sssaa');
            this.btnAdd = true;
            try {
                const valid = await this.$refs.formAdd.validate();
                if (!valid) {
                    this.$message.warning("表单验证未通过");
                    return;
                }

                const fields = [
                    'byline',
                    'title',
                    'publish_time',
                ];

                let data = new FormData();

                for (const key of fields) {
                    const value = this.formAdd[key];
                    if (value !== '' && value !== null && value !== undefined) {
                        data.append(key, value);
                    }
                }

                data.append('content', this.content);

                // 添加头像字段
                if (this.imageUrltx.file) {
                    data.append('avatar', this.imageUrltx.file);
                }

                // 添加图片字段
                if (this.imageUrlpt.file) {
                    data.append('image', this.imageUrlpt.file);
                }


                const res = await new_news_added(data);
                console.log(res, '新增');
                if (res?.status == "200" && res?.data?.code == "200") {

                    if (res.data.data) {
                        this.$notify({
                            title: `${res.data.message}`,
                            message: `ID:${res.data.data.id || ''}`,
                            type: 'success',
                            duration: 8000,
                            position: 'bottom-right'
                        });
                    } else {
                        this.$message.success(res.data.message || '成功')
                    }
                    this.get_data();
                    this.dialogVisibleAdd = false;
                } else {
                    this.$message.error(res?.data?.message || "操作失败");
                }
            } catch (err) {
                console.error(err);
                this.$message.error("请求失败，请稍后再试");
            } finally {
                this.btnAdd = false;
            }
        },
        // 更新
        async upd_data() {
            this.btnEdit = true;
            try {
                const valid = await this.$refs.formEdit.validate();
                if (!valid) {
                    this.$message.warning("表单验证未通过");
                    return;
                }

                const fields = [
                    'id',
                    'byline',
                    'title',
                    'publish_time',
                ];

                let data = new FormData();

                for (const key of fields) {
                    const value = this.formEdit[key];
                    if (value !== '' && value !== null && value !== undefined) {
                        data.append(key, value);
                    }
                }

                data.append('content', this.content);

                // 添加头像字段
                if (this.imageUrltx.file) {
                    data.append('avatar', this.imageUrltx.file);
                }

                // 添加图片字段
                if (this.imageUrlpt.file) {
                    data.append('image', this.imageUrlpt.file);
                }
                const response = await news_editor(this.formEdit.id, data);

                if (response.data && response.data.code == "200") {
                    this.$message.success(response.data.message);
                    this.dialogVisibleEdit = false;
                    this.get_data();
                } else {
                    this.$message.warning(response?.data?.msg || "操作失败");
                }
            } catch (err) {
                console.error("更新失败:", err);
                this.$message.error("请求出错，请稍后再试");
            } finally {
                this.btnEdit = false;
            }
        },
        // 删除
        async del_data(id) {
            try {
                await this.$confirm("是否继续执行操作？", "提示", {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning",
                });

                const res = await news_deletion(id).catch((err) => {
                    return console.error(err);
                });

                if (res && res.status == "200" && res.data.code == "200") {
                    this.$message.success(res.data.msg);
                    this.dialogVisibleAdd = false;
                    this.get_data();
                } else {
                    this.$message.error(res.data.message);
                }
            } catch (error) {
                // 用户点击取消或关闭对话框
                console.error(error);
            }
        },
        // 新增打开
        addbtn() {
            this.dialogVisibleAdd = true;
            this.titles = "新增";
            this.$nextTick(() => {
                this.editorReady = true
            })
        },
        // 编辑打开
        tableEditing(row) {
            this.$nextTick(() => {
                this.editorReady = true
            })
            this.titles = "编辑";
            this.dialogVisibleEdit = true;

            this.formEdit.id = row.id;

            this.formEdit.byline = row.byline;
            this.formEdit.title = row.title;
            this.formEdit.publish_time = row.publish_time;
            this.content = row.content



            if (row.image) {
                this.imageUrlpt.file = row.image;
                this.imageUrlpt.local = this.url + row.image;
            }
            if (row.avatar) {
                this.imageUrltx.file = row.avatar;
                this.imageUrltx.local = this.url + row.avatar;
            }

        },
        // 关闭弹窗
        beforeClose() {
            this.dialogVisibleEdit = false
            this.dialogVisibleAdd = false
            this.imageUrltx.local = ''
            this.imageUrltx.file = ''
            this.imageUrlpt.local = ''
            this.imageUrlpt.file = ''
            this.formAdd = {
                byline: '',
                title: '',
                publish_time: '',
            }
            this.formEdit = {
                id: '',
                byline: '',
                title: '',
                publish_time: '',
            }
            this.form = {
                keyword: "",
            }
            this.editorReady = false
            this.content = ''
        },

        // 分页
        current_change(currentPage) {
            this.currentPage = currentPage;
            this.get_data();
        },
        // 重置
        resetForm() {
            this.form = {
                keyword: "",
            }
            this.currentPage = 1;
            this.get_data();
        },
        onEditorBlur() {
            console.log('编辑器失焦')
        },
        onEditorFocus() {
            console.log('编辑器聚焦')
        },
        onEditorChange({ html, text }) {
            // console.log('内容变化:', html)
        },

        // 上传图片 + 插入编辑器
        async handleImageUpload(blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('file', blobInfo.blob(), blobInfo.filename())

            const res = await upload_pictures(formData);
            if (res.data && res.data.code == "200") {
                // 拿到服务器返回的图片 URL
                console.log(res, '上传图片res');

                success(this.url + res.data.data.image_url)

            } else {
                this.$message.warning(res?.data?.msg || "操作失败");
            }

        },

        // 插入图片到 Quill 编辑器
        insertToEditor(url) {
            const quill = this.$refs.myQuillEditor.quill;
            const range = quill.getSelection();
            const position = range ? range.index : quill.getLength();
            quill.insertEmbed(position, 'image', url);
            quill.setSelection(position + 1);
        },
        exportTable(format) {
            switch (format) {
                case 'json':
                    this.exportJSON();
                    break;
                case 'xml':
                    this.exportXML();
                    break;
                case 'csv':
                    this.exportCSV();
                    break;
                case 'txt':
                    this.exportTXT();
                    break;
                case 'word':
                    this.exportWord();
                    break;
                case 'excel':
                    this.exportExcel();
                    break;
            }
        },
        exportJSON() {
            const jsonStr = JSON.stringify(this.tableData, null, 2);
            const blob = new Blob([jsonStr], { type: 'application/json' });
            this.downloadBlob(blob, 'table.json');
        },
        exportXML() {
            const xml = `<?xml version="1.0"?>\n<rows>\n` +
                this.tableData.map(item =>
                    `  <row>\n` +
                    `    <id>${item.id}</id>\n` +
                    `    <avatar>${item.avatar}</avatar>\n` +
                    `    <byline>${item.byline}</byline>\n` +
                    `    <crawl_time>${item.crawl_time}</crawl_time>\n` +
                    `    <title>${item.title}</title>\n` +
                    `    <publish_time>${item.publish_time}</publish_time>\n` +
                    `  </row>`).join('\n') +
                `\n</rows>`;
            const blob = new Blob([xml], { type: 'application/xml' });
            this.downloadBlob(blob, 'table.xml');
        },
        exportCSV() {
            const headers = ['ID', '头像', '作者', '抓取时间', '标题', '发布时间', '封面图', '内容'];
            const rows = this.tableData.map(item => [
                item.id, item.avatar, item.byline, item.crawl_time, item.title, item.publish_time, item.image, item.content
            ]);
            let content = headers.join(',') + '\n';
            rows.forEach(row => {
                content += row.map(value => `"${String(value).replace(/"/g, '""')}"`).join(',') + '\n'; // 防止内容中含有逗号
            });
            const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
            this.downloadBlob(blob, 'table.csv');
        },
        exportTXT() {
            const headers = ['ID', '头像', '作者', '抓取时间', '标题', '发布时间', '封面图', '内容'];
            const rows = this.tableData.map(item => [
                item.id, item.avatar, item.byline, item.crawl_time, item.title, item.publish_time, item.image, item.content
            ]);
            let content = headers.join('\t') + '\n';
            rows.forEach(row => {
                content += row.join('\t') + '\n';
            });
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8;' });
            this.downloadBlob(blob, 'table.txt');
        },
        async exportWord() {
            const { default: HTMLDocx } = await import('html-docx-js/dist/html-docx');
            const html =
                `<table border="1" cellpadding="5" cellspacing="0">
        <tr><th>ID</th><th>头像</th><th>作者</th><th>抓取时间</th><th>标题</th><th>发布时间</th><th>封面图</th><th>内容</th></tr>` +
                this.tableData.map(item =>
                    `<tr>
                <td>${item.id}</td>
                <td>${item.avatar}</td>
                <td>${item.byline}</td>
                <td>${item.crawl_time}</td>
                <td>${item.title}</td>
                <td>${item.publish_time}</td>
                <td>${item.image}</td>
                <td>${item.content}</td>
            </tr>`
                ).join('') +
                `</table>`;
            const blob = HTMLDocx.asBlob(html);
            this.downloadBlob(blob, 'table.docx');
        },
        async exportExcel() {
            const XLSX = await import('xlsx');
            const ws = XLSX.utils.json_to_sheet(this.tableData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            const blob = new Blob([wbout], { type: 'application/octet-stream' });
            this.downloadBlob(blob, 'table.xlsx');
        },
        downloadBlob(blob, filename) {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            link.click();
            URL.revokeObjectURL(link.href);
        }
    },
};
</script>
<style>
.rowlist {
    padding: 6px !important;
}

.nbysm {
    flex: 2;
    text-align: right;
    line-height: 40px;
    font-weight: 700;
    font-size: 15px;
}

.souSuoYouCe {
    margin: 20px 0 0 auto;
    padding-bottom: 5px;
    padding-right: 10px;
}

.cell {
    font-size: 13px;
    white-space: nowrap !important;
}

.demo-table-expand {
    font-size: 0;
    margin-left: 10px;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>
<style lang="less" scoped>
.namename {
    padding: 0 10px;
    text-align: right;
    line-height: 40px;
    font-weight: 700;
    font-size: 15px;
    display: flex;
    align-items: center;
}

.el-textarea {
    overflow: hidden;
    /* 隐藏滚动条 */
}

.pageListBox {
    width: 100%;
    // padding: 10px;
    // background-color: aquamarine;
    height: auto;
    // border: 1px #000 solid;

    .cardAdmin {
        position: relative;
        // height: 18%;
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        margin: 0;

        // border: #fafafa solid 1px;
        padding: 0 5px;
        margin-bottom: 2px;

        .formNewAdmin {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            padding: 0;
            align-self: baseline;
            padding-bottom: 10px;
            border-bottom: 1px #e3e3e3 solid;
        }

        .formSearch {
            width: 25%;
            min-width: 25%;
            margin-top: 20px;
            height: 30px;
            display: flex;
            justify-content: center;
        }
    }

    .btnBoxList {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;

        .formbtns {
            width: 50%;
            display: flex;
            justify-content: end;
            padding: 5px 10px;

            .qweqweasdasd {
                width: 75px;
                padding: 5px 10px;
                border: 1px #f4f4f4 solid;
            }

            .qweqweasdasd:hover {

                background-color: #e7e7e7;
                border: 1px #ccc solid;
            }

            .btnList22 {
                width: auto;
                height: 28px;
                color: #000;
                min-width: 50px;
                border-radius: 0px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;

                i {
                    font-size: 18px;
                }
            }

        }

        .btns {
            width: 50%;
            display: flex;
            padding: 5px 10px;



        }


    }

    .pop-up-form {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        padding: 0;
        align-self: baseline;
        margin: 10px 0;
        justify-content: center;
        padding-right: 15px;

        .form-options {
            width: 100%;
            min-width: 100%;
            height: 40px;
            display: flex;
            justify-content: center;
            margin: 10px 0;
        }
    }
}
</style>
<style lang="less">
.cell {
    font-size: 13px;
    white-space: nowrap !important;
}

textarea {
    resize: none !important;
}

/* 子级样式 */
.child-row11 {
    background-color: #fcfcfc !important;
    color: #ff8718;
}

/* 父级样式 */
.parent-row11 {
    background-color: #ffffff;
    color: #000;
    font-weight: 500;
}

.parent-row11 .cell {
    font-size: 13px !important;
}

.el-dropdown-link {
    height: 100%;
    cursor: pointer;
    color: #000;
    font-weight: bold;
    font-size: 14px;
    display: flex;
    align-items: center;
}

.fenye11 {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    padding: 4px 8px;
}



.el-pager li.active {
    background-color: #000 !important;
}

.setFomr {
    display: flex;
    align-items: center;
    padding: 10px 10px 0 10px;
}



.resetForm-button {
    background-color: #ffffff !important;
    border-color: #333 !important;
    color: #333 !important;
    font-size: 13px !important;
}

.resetForm-button:hover {
    background-color: #fff !important;
    border-color: #333 !important;
}

.dialogqp {
    left: 0 !important;
    top: 0 !important;

    .el-dialog__body {
        height: calc(100vh - 113px) !important;
    }


}

.dialogTitle {
    position: absolute;
    top: 20px;
    right: 50px;
    padding: 0;
    background: 0 0;
    border: none;
    outline: 0;
    cursor: pointer;
    font-size: 16px;
}

.dialogTitle * {
    color: #fff !important;
}

.diaformart {
    input {
        background-color: #fff !important;
        color: #000 !important;
    }
}
</style>
  